<template>
  <div class="map-location-picker">
    <!-- 搜索栏 -->
    <div class="search-container">
      <a-input-search
        v-model:value="searchKeyword"
        placeholder="搜索地点（如：北京大学、天安门、中关村）"
        enter-button="搜索"
        size="large"
        :loading="searchLoading"
        @search="handleSearch"
        @pressEnter="handleSearch"
        class="search-input"
      >
        <template #prefix>
          <SearchOutlined />
        </template>
      </a-input-search>
    </div>

    <!-- 操作提示 -->
    <div class="tip-container">
      <a-alert
        message="使用说明"
        description="🔍 在搜索框中输入地点名称进行搜索 | 📍 点击红色标记选择地点 | 🔵 拖拽蓝色标记调整位置 | 📍 点击地图任意位置设置新位置 | ✅ 点击确定选择按钮保存位置"
        type="info"
        show-icon
        closable
      />
    </div>

    <!-- 地图容器 -->
    <div class="map-container">
      <div id="enhancedMapContainer" :style="{ height: mapHeight }"></div>
    </div>

    <!-- 当前选择信息 -->
    <div v-if="currentLocation" class="location-info">
      <a-card size="small" title="当前选择的位置">
        <div class="location-details">
          <div class="location-name">
            <EnvironmentOutlined style="color: #1890ff" />
            <strong>{{ currentLocation.name || '未命名位置' }}</strong>
          </div>
          <div class="location-address">📍 {{ currentLocation.address }}</div>
          <div class="location-coords">
            🌐 经度: {{ currentLocation.longitude.toFixed(6) }} | 纬度:
            {{ currentLocation.latitude.toFixed(6) }}
          </div>
          <div v-if="currentLocation.city" class="location-area">
            🏙️ {{ currentLocation.province }}{{ currentLocation.city
            }}{{ currentLocation.district }}
          </div>
        </div>
      </a-card>
    </div>

    <!-- 操作按钮 -->
    <div class="action-buttons">
      <a-space>
        <a-button @click="handleCancel"> 取消 </a-button>
        <a-button type="primary" :disabled="!currentLocation" @click="handleConfirm">
          确定选择
        </a-button>
      </a-space>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, defineEmits, defineProps, nextTick, watch } from 'vue'
import { message } from 'ant-design-vue'
import { SearchOutlined, EnvironmentOutlined } from '@ant-design/icons-vue'
import { createEnhancedLocationPicker, type LocationInfo } from '../utils/mapUtils'

interface Props {
  visible?: boolean
  initialLocation?: { longitude: number; latitude: number }
  mapHeight?: string
}

interface Emits {
  (e: 'confirm', location: LocationInfo): void
  (e: 'cancel'): void
}

const props = withDefaults(defineProps<Props>(), {
  visible: true,
  mapHeight: '400px',
})

const emit = defineEmits<Emits>()

// 搜索相关
const searchKeyword = ref('')
const searchLoading = ref(false)

// 地图相关
const currentLocation = ref<LocationInfo | null>(null)
let mapInstance: any = null

// 处理搜索（点击搜索按钮）
const handleSearch = async () => {
  if (!searchKeyword.value.trim()) {
    message.warning('请输入搜索关键词')
    return
  }

  if (!mapInstance) {
    message.error('地图未初始化完成，请稍后再试')
    return
  }

  try {
    searchLoading.value = true

    // 检查地图实例是否有搜索方法
    if (!mapInstance.searchNearby) {
      message.error('地图搜索功能未就绪，请刷新页面重试')
      return
    }

    await mapInstance.searchNearby(searchKeyword.value.trim())
    // 搜索成功的消息在mapUtils中处理
  } catch (error) {
    console.error('搜索失败:', error)

    // 根据错误类型提供具体的解决建议
    const errorMessage = error instanceof Error ? error.message : String(error)

    if (errorMessage.includes('USERKEY_PLAT_NOMATCH')) {
      message.error('API密钥平台配置错误！请在高德控制台同时勾选"Web端(JS API)"和"Web服务"两个平台')
    } else if (errorMessage.includes('INVALID_USER_KEY')) {
      message.error('API密钥无效！请检查环境变量 VITE_AMAP_KEY 配置是否正确')
    } else if (errorMessage.includes('安全密钥')) {
      message.error('安全密钥配置错误！请检查环境变量 VITE_AMAP_SECURITY_CODE 配置')
    } else {
      message.error('搜索功能暂时不可用，请稍后重试')
    }
  } finally {
    searchLoading.value = false
  }
}

// 处理位置选择
const handleLocationSelect = (location: LocationInfo) => {
  currentLocation.value = location
}

// 处理直接确认（从信息窗口点击确认按钮）
const handleDirectConfirm = (location: LocationInfo) => {
  currentLocation.value = location
  emit('confirm', location)
  message.success(`已确认选择：${location.name || location.address}`)
}

// 处理确认
const handleConfirm = () => {
  if (!currentLocation.value) {
    message.warning('请先选择一个位置')
    return
  }

  emit('confirm', currentLocation.value)
  message.success(`已确认选择：${currentLocation.value.name || currentLocation.value.address}`)
}

// 处理取消
const handleCancel = () => {
  emit('cancel')
}

// 初始化地图
const initMap = async () => {
  try {
    // 检查地图容器是否存在
    const container = document.getElementById('enhancedMapContainer')
    if (!container) {
      console.error('地图容器未找到')
      message.error('地图容器初始化失败，请刷新页面重试')
      return
    }

    mapInstance = await createEnhancedLocationPicker(
      'enhancedMapContainer',
      handleLocationSelect, // 位置选择回调（当拖拽、点击地图时触发）
      handleDirectConfirm, // 直接确认回调（当点击信息窗口确认按钮时触发）
      props.initialLocation
    )

    // 如果有初始位置，获取当前位置信息
    if (props.initialLocation || mapInstance.getCurrentLocation()) {
      const location = mapInstance.getCurrentLocation()
      if (location) {
        currentLocation.value = location
      }
    }
  } catch (error) {
    console.error('地图初始化失败:', error)

    // 根据错误类型提供具体的错误信息
    const errorMessage = error instanceof Error ? error.message : String(error)

    if (errorMessage.includes('USERKEY_PLAT_NOMATCH')) {
      message.error(
        '地图服务配置错误！请确保在高德控制台同时勾选了"Web端(JS API)"和"Web服务"两个平台'
      )
    } else if (errorMessage.includes('INVALID_USER_KEY')) {
      message.error('地图密钥无效！请检查环境变量配置')
    } else if (errorMessage.includes('安全密钥')) {
      message.error('地图安全密钥配置错误！请检查 VITE_AMAP_SECURITY_CODE 配置')
    } else if (errorMessage.includes('网络')) {
      message.error('网络连接异常，请检查网络后重试')
    } else {
      message.error('地图服务暂时不可用，请稍后重试')
    }

    // 将mapInstance设为null，避免后续操作报错
    mapInstance = null
  }
}

// 监听visible变化，重新初始化地图
watch(
  () => props.visible,
  async (newVisible) => {
    if (newVisible && !mapInstance) {
      await nextTick()
      setTimeout(() => {
        initMap()
      }, 200)
    }
  }
)

// 生命周期
onMounted(async () => {
  if (props.visible) {
    // 确保DOM元素已渲染
    await nextTick()

    // 稍微延迟确保容器完全可用
    setTimeout(() => {
      initMap()
    }, 200)
  }
})

onUnmounted(() => {
  if (mapInstance && mapInstance.destroy) {
    mapInstance.destroy()
    mapInstance = null
  }
})

// 暴露方法给父组件
defineExpose({
  setLocation: (lng: number, lat: number) => {
    if (mapInstance && mapInstance.setLocation) {
      mapInstance.setLocation(lng, lat)
    }
  },
  getCurrentLocation: () => {
    return mapInstance?.getCurrentLocation?.() || currentLocation.value
  },
})
</script>

<style scoped>
.map-location-picker {
  padding: 16px;
}

.search-container {
  margin-bottom: 16px;
}

.search-input {
  width: 100%;
}

.tip-container {
  margin-bottom: 16px;
}

.map-container {
  margin-bottom: 16px;
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  overflow: hidden;
}

.location-info {
  margin-bottom: 16px;
}

.location-details {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.location-name {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  color: #1890ff;
}

.location-address,
.location-coords,
.location-area {
  color: #666;
  font-size: 14px;
  line-height: 1.5;
}

.action-buttons {
  display: flex;
  justify-content: flex-end;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .map-location-picker {
    padding: 12px;
  }

  .location-details {
    font-size: 13px;
  }

  .location-name {
    font-size: 14px;
  }
}
</style> 